package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.PatientCosts;
import com.ruoyi.system.domain.Register;
import com.ruoyi.system.service.IPatientCostsService;
import com.ruoyi.system.service.IRegisterService;
import com.ruoyi.system.service.impl.RegistLevelServiceImpl;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.web.controller.tool.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 挂号Controller
 *
 * @author ruoyi
 * @date 2023-07-04
 */
@Api(tags = "挂号模块")
@RestController
@RequestMapping("/system/Register")
public class RegisterController extends BaseController {
    @Autowired
    private IRegisterService registerService;
    @Autowired
    IPatientCostsService patientCostsService;
    static int sequence = 0;

    private class Wrap implements Serializable {

        Register Register;
        String DeptId;
        String UserId;
        String RegistLevelId;
        String RegisterId;

        @JsonProperty("RegisterId")
        public String getRegisterId() {
            return RegisterId;
        }

        @JsonProperty("Register")
        public Register getRegister() {
            return Register;
        }

        @JsonProperty("DeptId")
        public String getDeptId() {
            return DeptId;
        }

        @JsonProperty("UserId")
        public String getUserId() {
            return UserId;
        }

        @JsonProperty("RegistLevelId")
        public String getRegistLevelId() {
            return RegistLevelId;
        }
    }

    @Autowired
    SysDeptServiceImpl sysDeptService;
    @Autowired
    SysUserServiceImpl sysUserService;
    @Autowired
    RegistLevelServiceImpl registLevelService;


    private Wrap convert(Register origin) {
        Wrap tempWrap = new Wrap();
        tempWrap.DeptId = sysDeptService.selectDeptById(origin.getDeptId()).getDeptName();
        tempWrap.UserId = sysUserService.selectUserById(origin.getRegisterId()).getUserName();
        tempWrap.RegistLevelId = registLevelService.getById(origin.getRegistLevelId()).getRegistName();
        tempWrap.Register = origin;
        return tempWrap;
    }


    /**
     * 查询挂号列表
     */
    @ApiOperation(value = "查询挂号列表")
    @PreAuthorize("@ss.hasPermi('system:Register:list')")
    @GetMapping("/list")
    public Page<Wrap> list(Register entity, Page<Register> page) {
        QueryWrapper<Register> queryWrapper = new QueryWrapper<Register>();

        if (entity.getRealName() != null) {
            queryWrapper.like("RealName", entity.getRealName());
        }
        if (entity.getVisitState() != null) {
            queryWrapper.eq("VisitState", entity.getVisitState());
        }
        queryWrapper.orderByDesc("RegisterTime");
        Page<Register> old = registerService.page(page, queryWrapper);
        List<Register> object = old.getRecords();
        Page<Wrap> pageWrap = new Page<>();
        List<Wrap> wraps = new ArrayList<>();
        for (Register item : object) {
            wraps.add(convert(item));
        }
        pageWrap.setRecords(wraps);
        PageUtil pageUtil = new PageUtil();
        pageUtil.setPage(pageWrap, old);
        return pageWrap;
    }

    /**
     * 生成病历号
     */
    @GetMapping("/caseNumber")
    public String generateCaseNumber() {
        String caseNumber = "his";
        LocalDate date = LocalDate.now();
        String date1 = date.toString();
        date1.replace("-", "");
        caseNumber = caseNumber + date1 + sequence;
        sequence++;
        return caseNumber;
    }

    /**
     * 导出挂号列表
     */
    @ApiOperation(value = "导出挂号列表")
    @PreAuthorize("@ss.hasPermi('system:Register:export')")
    @Log(title = "挂号", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Register register) {
        LambdaQueryWrapper<Register> queryWrapper = new LambdaQueryWrapper<>();
        List<Register> list = registerService.list(queryWrapper);
        ExcelUtil<Register> util = new ExcelUtil<Register>(Register.class);
        util.exportExcel(response, list, "挂号数据");
    }


    /**
     * 获取挂号详细信息
     */
    @ApiOperation(value = "获取挂号详细信息")
    @PreAuthorize("@ss.hasPermi('system:Register:query')")
    @GetMapping(value = "/{Id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(registerService.getById(id));
    }

    /**
     * 新增挂号并生成收费条目
     */
    @ApiOperation(value = "新增挂号")
    @PreAuthorize("@ss.hasPermi('system:Register:add')")
    @Log(title = "挂号", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Register register) {
        if (registerService.save(register)) {
            PatientCosts patientCosts = new PatientCosts();
            patientCosts.setRegisterId(register.getId());
            patientCosts.setPrice(registLevelService.getById(register.getRegistLevelId()).getRegistFee());//设置价格
            patientCosts.setItemId(1L);
            patientCosts.setState(0L);
            if (patientCostsService.save(patientCosts)) {
                return AjaxResult.success(generateCaseNumber());
            }
        }
        return AjaxResult.error();
    }

    /**
     * 修改挂号
     */
    @ApiOperation(value = "修改挂号")
    @PreAuthorize("@ss.hasPermi('system:Register:edit')")
    @Log(title = "挂号", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Register register) {
        return toAjax(registerService.updateById(register));
    }

    /**
     * 修改缴费状态
     */
    @PutMapping("/setState")
    public AjaxResult setState(@RequestBody PatientCosts patientCosts) {
        return toAjax(patientCostsService.updateById(patientCosts));
    }

    /**
     * 删除挂号
     */
    @ApiOperation(value = "删除挂号")
    @PreAuthorize("@ss.hasPermi('system:Register:remove')")
    @Log(title = "挂号", businessType = BusinessType.DELETE)
    @DeleteMapping("/{Ids}")
    public AjaxResult remove(@PathVariable Long[] Ids) {
        return toAjax(registerService.removeBatchByIds(Arrays.asList(Ids)));
    }

    /**
     * 通过姓名查询
     */
    @GetMapping("/selectByName")
    public Wrap selectByName(@PathVariable String name) {
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq("RealName", name);
        Register registerSe = registerService.getOne(lambdaQueryWrapper);
        return convert(registerSe);
    }

    /**
     * 通过身份证号查询
     */
    @GetMapping("/selectByIDNumber")
    public Wrap selectByIDNumber(@PathVariable String IDNumber) {
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq("IDNumber", IDNumber);
        Register registerSe = registerService.getOne(lambdaQueryWrapper);
        return convert(registerSe);
    }

    /**
     * 通过病历号查询
     */
    @GetMapping("/selectByCaseNumber")
    public Wrap selectByCaseNumber(@PathVariable String CaseNumber) {
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq("CaseNumber", CaseNumber);
        Register registerSe = registerService.getOne(lambdaQueryWrapper);
        return convert(registerSe);
    }

    @GetMapping("/selectByVisitState")
    public List<Wrap> selectByCaseNumber(@PathVariable Long VisitState) {
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq("VisitState", VisitState);
        List<Register> registerSe = registerService.list(lambdaQueryWrapper);
        List<Wrap> wrap = new ArrayList<>();
        for (Register item : registerSe) {
            wrap.add(convert(item));
        }
        return wrap;
    }

}
